package com.sn.utils;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;

import javax.sql.DataSource;

import com.alibaba.druid.pool.DruidDataSourceFactory;

public class JdbcUtils {

	private static DataSource dataSource;
	static{
		try {
			Properties p = new Properties();
			ClassLoader loader = Thread.currentThread().getContextClassLoader();
			InputStream inStream = loader.getResourceAsStream("db.properties");
			p.load(inStream);
			dataSource = DruidDataSourceFactory.createDataSource(p);
		} catch (Exception e) {
			throw new RuntimeException("连接数据库加载properties文件失败");
		}
	}
	

	public static Connection getConn() {
		try {
			return dataSource.getConnection();
		} catch (Exception e) {
			e.printStackTrace();
		}
		throw new RuntimeException("连接数据库失败");
	}
	

	public static void close(Connection conn, PreparedStatement ps, ResultSet rs) {
		try {
			if (rs!=null) {
				rs.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				if(ps!=null){
					ps.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				try {
					if (conn != null) {
						conn.close();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	
}
